<template>
  <div class="login-container animated-background">
    <!-- SVG滤镜库（保持新页面样式） -->
    <svg style="display: none">
      <filter id="glass-distortion" x="0%" y="0%" width="100%" height="100%" filterUnits="objectBoundingBox">
        <feTurbulence type="fractalNoise" baseFrequency="0.001 0.005" numOctaves="1" seed="17" result="turbulence" />
        <feComponentTransfer in="turbulence" result="mapped">
          <feFuncR type="gamma" amplitude="1" exponent="10" offset="0.5" />
          <feFuncG type="gamma" amplitude="0" exponent="1" offset="0" />
          <feFuncB type="gamma" amplitude="0" exponent="1" offset="0.5" />
        </feComponentTransfer>
        <feGaussianBlur in="turbulence" stdDeviation="3" result="softMap" />
        <feSpecularLighting in="softMap" aceScale="5" specularConstant="1" specularExponent="100" lighting-color="white" result="specLight">
          <fePointLight x="-200" y="-200" z="300" />
        </feSpecularLighting>
        <feComposite in="specLight" operator="arithmetic" k1="0" k2="1" k3="1" k4="0" result="litImage" />
        <feDisplacementMap in="SourceGraphic" in2="softMap" scale="200" xChannelSelector="R" yChannelSelector="G" />
      </filter>
    </svg>

    <!-- 登录卡片（保留新页面交互效果） -->
    <div
      ref="tiltCard"
      class="glass-component login-card"
      @mousemove="handleMouseMove"
      @mouseleave="handleMouseLeave"
    >
      <div class="glass-effect" />
      <div class="glass-tint" />
      <div class="glass-shine" />
      <div class="glass-content">
        <h2 class="login-title">鸿科报表系统</h2>
        <!-- 表单：去除图标，使用Element Plus原生特性 -->
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          auto-complete="on"
          @submit.prevent="handleLogin"
        >
          <!-- 用户名输入框：去除图标，保留clearable -->
          <el-form-item prop="username" class="form-group">
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="请输入用户名"
              name="username"
              type="text"
              tabindex="1"
              auto-complete="on"
              class="glass-input"
              clearable
            />
          </el-form-item>

          <!-- 密码输入框：去除图标，使用Element Plus原生show-password -->
          <el-form-item prop="password" class="form-group">
            <el-input
              ref="password"
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              name="password"
              tabindex="2"
              auto-complete="on"
              class="glass-input"
              show-password
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>

          <!-- 登录按钮（保持新页面样式） -->
          <el-form-item>
            <el-button
              :loading="loading"
              type="primary"
              class="glass-button"
              @click.native.prevent="handleLogin"
            >登录</el-button>
          </el-form-item>
        </el-form>

      </div>
    </div>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { mapState } from 'vuex'

export default {
  name: 'Login',
  data() {
    // 保留你原有的验证规则
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能少于6位'))
      } else {
        callback()
      }
    }

    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ]
      },
      loading: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    // 保留你原有的路由监听
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
        this.otherQuery = this.getOtherQuery(route.query)
      },
      immediate: true
    },
    // 保留iframe自动登录监听
    iframeInfo: function(val) {
      if (val.username && val.password) {
        this.loginForm.username = val.username
        this.loginForm.password = val.password
        this.handleLogin()
      }
    }
  },
  computed: {
    // 保留Vuex状态映射
    ...mapState({
      iframeInfo: (state) => state.user.iframeInfo
    })
  },
  created() {},
  mounted() {
    // 输入框自动聚焦
    this.$nextTick(() => {
      this.$refs.username?.focus()
    })
  },
  methods: {
    // 保留你原有的所有方法
    getOtherQuery(query) {
      const { redirect, ...otherQuery } = query
      return otherQuery
    },

    // 登录核心逻辑（完全使用你的代码）
    handleLogin() {
      this.$refs.loginForm.validate(async(valid) => {
        if (valid) {
          this.loading = true
          try {
            await this.$store.dispatch('user/login', this.loginForm)
            const { roles } = await this.$store.dispatch('user/getInfo')
            const accessRoutes = await this.$store.dispatch(
              'permission/generateRoutes',
              roles
            )
            this.$router.addRoutes(accessRoutes)
            this.$router.push({
              path: this.redirect || '/dashboard',
              query: this.otherQuery
            })
            this.loading = false
          } catch (err) {
            console.log('登录失败:', err)
            this.loading = false
          }
        } else {
          console.log('表单验证失败!!')
          return false
        }
      })
    },

    // 保留新页面的3D倾斜交互
    handleMouseMove(e) {
      const card = this.$refs.tiltCard
      if (!card) return

      const rect = card.getBoundingClientRect()
      const x = e.clientX - rect.left
      const y = e.clientY - rect.top
      const centerX = rect.width / 2
      const centerY = rect.height / 2

      const maxTilt = 18
      const rotateY = ((x - centerX) / centerX) * maxTilt
      const rotateX = -((y - centerY) / centerY) * maxTilt

      card.style.transform = `perspective(600px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale(1.03)`
    },

    handleMouseLeave() {
      const card = this.$refs.tiltCard
      if (card) {
        card.style.transform = 'perspective(600px) rotateX(0deg) rotateY(0deg) scale(1)'
      }
    }
  }
}
</script>

<!-- 完全使用新页面的样式，去除图标相关样式 -->
<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  padding: 20px;
}

.animated-background {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg,
    #667eea 0%,
    #764ba2 25%,
    #f093fb 50%,
    #f5576c 75%,
    #4facfe 100%);
  background-size: 400% 400%;
  animation: gradientShift 15s ease infinite;
  position: relative;
}

@keyframes gradientShift {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.login-card {
  width: 100%;
  max-width: 400px;
  position: relative;
  border-radius: 24px;
  overflow: hidden;
  box-shadow:
    0 4px 24px 0 rgba(0,0,0,0.10),
    0 1.5px 6px 0 rgba(0,0,0,0.08);
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.6);
  cursor: default;
  background: transparent;
}

.glass-effect {
  position: absolute;
  inset: 0;
  z-index: 0;
  backdrop-filter: blur(5px);
  filter: url(#glass-distortion);
  isolation: isolate;
  border-radius: 24px;
}

.glass-tint {
  position: absolute;
  inset: 0;
  z-index: 1;
  background: rgba(0, 0, 0, 0.15);
  border-radius: 24px;
}

.glass-shine {
  position: absolute;
  inset: 0;
  z-index: 2;
  border: 1px solid rgba(255, 255, 255, 0.13);
  border-radius: 24px;
  box-shadow:
    inset 1px 1px 8px 0 rgba(255, 255, 255, 0.18),
    inset -1px -1px 8px 0 rgba(255, 255, 255, 0.08);
  pointer-events: none;
}

.glass-content {
  position: relative;
  z-index: 3;
  padding: 2.5rem 2rem;
  color: white;
}

.login-title {
  text-align: center;
  color: #fff;
  margin-bottom: 2rem;
  font-size: 2rem;
  font-weight: 600;
  text-shadow: 0 1px 3px rgba(0,0,0,0.2);
}

.form-group {
  margin-bottom: 1.5rem;
}

/* 玻璃质感输入框（适配Element Plus，无图标） */
.glass-input {
  width: 100%;
  --el-input-bg-color: rgba(255, 255, 255, 0.1);
  --el-input-text-color: #fff;
  --el-input-placeholder-color: rgba(255, 255, 255, 0.7);
  --el-input-border-color: transparent;
  --el-input-focus-border-color: transparent;
  --el-input-focus-bg-color: rgba(255, 255, 255, 0.2);
  --el-input-hover-bg-color: rgba(255, 255, 255, 0.15);
  border-radius: 10px;
  backdrop-filter: blur(5px);

  .el-input__wrapper {
    border-radius: 10px !important;
    box-shadow: none !important;
  }

  .el-input__inner {
    padding: 12px 20px !important;
    font-size: 1rem !important;
    height: 50px !important;
  }

  &:focus-within {
    box-shadow: 0 0 15px rgba(255, 255, 255, 0.1);
  }
}

/* 玻璃质感按钮 */
.glass-button {
  width: 100%;
  padding: 12px;
  border: none;
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
  position: relative;
  overflow: hidden;
  height: 50px;

  &:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
  }

  &:active {
    transform: translateY(0);
  }
}

.login-footer {
  text-align: center;
  margin-top: 1.5rem;

  p {
    color: rgba(255, 255, 255, 0.8);
    font-size: 0.9rem;
    text-shadow: 0 1px 2px rgba(0,0,0,0.1);
    margin: 0;
  }
}

.glass-component {
  transition: transform 0.25s cubic-bezier(0.22, 1, 0.36, 1);
  will-change: transform;
}

/* 点击波纹效果 */
.click-gradient {
  position: absolute;
  border-radius: 50%;
  background: radial-gradient(circle,
    rgba(255,255,255,0.4) 0%,
    rgba(180,180,255,0.2) 40%,
    rgba(100,100,255,0.1) 70%,
    rgba(50,50,255,0) 100%);
  transform: translate(-50%, -50%) scale(0);
  opacity: 0;
  pointer-events: none;
  z-index: 4;
}

.glass-component.clicked .click-gradient {
  animation: gradient-ripple 0.6s ease-out;
}

@keyframes gradient-ripple {
  0% {
    transform: translate(-50%, -50%) scale(0);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(3);
    opacity: 0;
  }
}

/* 错误提示样式适配 */
.el-form-item__error {
  background: transparent !important;
  color: rgba(255, 255, 255, 0.9) !important;
  text-shadow: 0 1px 2px rgba(0,0,0,0.2) !important;
  padding-left: 0 !important;
  margin-top: 6px !important;
  font-size: 0.9rem;
}

/* 加载动画颜色调整 */
.el-loading-spinner .path {
  stroke: rgba(255, 255, 255, 0.8) !important;
}

/* 响应式适配 */
@media (max-width: 480px) {
  .login-card {
    max-width: 100%;
  }

  .glass-content {
    padding: 2rem 1.5rem;
  }

  .login-title {
    font-size: 1.8rem;
  }

  .glass-input .el-input__inner {
    height: 45px !important;
  }

  .glass-button {
    height: 45px;
  }
}
</style>

<!-- 全局样式覆盖（确保Element Plus组件适配玻璃效果） -->
<style lang="scss">
.login-container {
  .el-input__clear {
    color: rgba(255, 255, 255, 0.7) !important;
  }

  .el-input-password__eye {
    color: rgba(255, 255, 255, 0.7) !important;
    &:hover {
      color: #fff !important;
    }
  }

  .el-button--primary.is-loading {
    background: rgba(255, 255, 255, 0.15) !important;
    color: rgba(255, 255, 255, 0.8) !important;
  }
}
</style>
